package com.dd.cloud.user.service.phar.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.user.entity.phar.PharFryingOneRule;
import com.dd.cloud.user.entity.phar.PharFryingTwoRule;
import com.dd.cloud.user.entity.phar.PharmacyChoose;
import com.dd.cloud.user.entity.phar.PharmacyRelatedProvince;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.user.mapper.phar.PharmacyChooseMapper;
import com.dd.cloud.user.mapper.phar.PharmacyRelatedProvinceMapper;
import com.dd.cloud.user.res.phar.PharmacyChooseRes;
import com.dd.cloud.user.service.phar.IPharFryingOneRuleService;
import com.dd.cloud.user.service.phar.IPharFryingTwoRuleService;
import com.dd.cloud.user.service.phar.IPharmacyChooseService;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 机构的选择默认药房表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-09-23
 */
@Service
public class PharmacyChooseServiceImpl extends ServiceImpl<PharmacyChooseMapper, PharmacyChoose> implements IPharmacyChooseService {
    @Autowired
    private PharmacyRelatedProvinceMapper pharmacyRelatedProvinceMapper;

    /**
     * 查询机构或医生默认选中药房
     *
     * @param mechanId
     * @return
     */
    @Override
    public List<PharmacyChooseRes> getPharChooseListByMechan(Integer mechanId) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        Integer doctorId = loginInfo.getId();
        if (mechanId == null) {
            mechanId = loginInfo.getMechanId();
            List<PharmacyChooseRes> list = getBaseMapper().getPharChooseListByMechan(mechanId, doctorId);
            if (list != null && !list.isEmpty()) {
                for (PharmacyChooseRes item : list) {
                    if (item.getIsRegionLimit() == 0) {
                        item.setIsOpt(1);
                    }
                }
                return list;
            }
        }
        List<PharmacyChooseRes> list = getBaseMapper().getPharChooseListByMechanOrDoctor(null, doctorId);
        Map<Integer, PharmacyRelatedProvince> map = getNearPharmacy(mechanId, loginInfo);
        for (PharmacyChooseRes item : list) {
            if (map.get(item.getPharId()) != null || item.getIsRegionLimit() == 0) {
                item.setIsOpt(1);
            }
        }
        return list;
    }

    /**
     * 查询机构的默认使用药房
     *
     * @param mechanId
     * @return
     */
    @Override
    public PharmacyChooseRes getPharChooseByMechan(Integer mechanId) {
        PharmacyChooseRes res = null;
        List<PharmacyChooseRes> list = getPharChooseListByMechan(mechanId);
        for (PharmacyChooseRes item : list) {
            if (item.getChoose() == 1) {
                res = item;
            }
        }
        if (res == null) {
            LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
            Map<Integer, PharmacyRelatedProvince> map = getNearPharmacy(mechanId, loginInfo);
            for (PharmacyChooseRes item : list) {
                if (map.get(item.getPharId()) != null) {
                    //设置加工类型
                    item.setType(getType(item.getPharId()));
                    res = item;
                    break;
                }
            }
        }
        if (res == null) {
            PharmacyChooseRes pcr = list.get(0);
            if (pcr != null && pcr.getPharId() != null) {
                pcr.setType(getType(pcr.getPharId()));
            }
            return pcr;
        }
        return res;
    }

    public Map<Integer, PharmacyRelatedProvince> getNearPharmacy(Integer mechanId, LoginInfo loginInfo) {
        List<PharmacyRelatedProvince> selectList = pharmacyRelatedProvinceMapper.getPharRelatedDoctor(loginInfo.getId());
        if (selectList == null || selectList.isEmpty()) {
            if (mechanId == null) {
                mechanId = loginInfo.getMechanId();
            }
            selectList = pharmacyRelatedProvinceMapper.getPharRelatedMechan(mechanId);
        }
        return selectList.stream().collect(Collectors.toMap(PharmacyRelatedProvince::getPharId, t -> t));
    }

    @Autowired
    private IPharFryingOneRuleService pharFryingOneRuleService;
    @Autowired
    private IPharFryingTwoRuleService pharFryingTwoRuleService;

    public Integer getType(Integer pharId) {
        LambdaQueryWrapper<PharFryingOneRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PharFryingOneRule::getIsChecked, 1)
                .orderByAsc(PharFryingOneRule::getType)
                .eq(PharFryingOneRule::getPharId, pharId)
                .eq(PharFryingOneRule::getStatus,1);
        List<PharFryingOneRule> pharFryingOneRuleList = pharFryingOneRuleService.getBaseMapper().selectList(wrapper);
        if (CollectionUtil.isNotEmpty(pharFryingOneRuleList)) {
            return pharFryingOneRuleList.get(0).getType();
        } else {
            LambdaQueryWrapper<PharFryingTwoRule> qw = new LambdaQueryWrapper<>();
            qw.eq(PharFryingTwoRule::getIsChecked, 1)
                    .orderByAsc(PharFryingTwoRule::getType)
                    .eq(PharFryingTwoRule::getPharId, pharId)
                    .eq(PharFryingTwoRule::getStatus,1);
            List<PharFryingTwoRule> pharFryingTwoRuleList = pharFryingTwoRuleService.getBaseMapper().selectList(qw);
            if (CollectionUtil.isNotEmpty(pharFryingTwoRuleList)) {
                return pharFryingTwoRuleList.get(0).getType();
            }
        }
        return -1;
    }

    /**
     * 添加或修改机构的默认使用药房
     *
     * @param pharId
     * @param mechanId
     * @param doctorId
     */
    @Override
    public void saveOrUpdatePharChooseByMechanId(Integer pharId, Integer mechanId, Integer doctorId, Integer type) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (loginInfo.getType() == LoginInfo.UserType.DOCTOR && doctorId == null) {
            doctorId = loginInfo.getId();
        }
        if (loginInfo.getType() == LoginInfo.UserType.ADMIN && mechanId == null) {
            throw new ZekeException(ZkExceptionEnum.PARAMETER_ERROR, "机构id不能为空");
        }
        UpdateWrapper<PharmacyChoose> uw = new UpdateWrapper<>();
        if (mechanId != null) {
            uw.lambda().eq(PharmacyChoose::getMechanId, mechanId);
        }
        if (doctorId != null) {
            uw.lambda().eq(PharmacyChoose::getDoctorId, doctorId);
        }
        uw.lambda().set(PharmacyChoose::getPharId, pharId);
        uw.lambda().set(PharmacyChoose::getType, type);
        boolean flag = update(uw);
        if (!flag) {
            PharmacyChoose pc = new PharmacyChoose();
            pc.setMechanId(mechanId);
            pc.setDoctorId(doctorId);
            pc.setPharId(pharId);
            pc.setIsPay(1);
            pc.setType(type);
            save(pc);
        }
    }
}
